import React, { useState } from 'react';
import {
  Box,
  Card,
  CardContent,
  Grid,
  Typography,
  Button,
  Chip,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Alert,
  List,
  ListItem,
  ListItemText,
  ListItemIcon,
  IconButton,
  Tooltip,
  Divider,
} from '@mui/material';
import {
  Add as AddIcon,
  Edit as EditIcon,
  Delete as DeleteIcon,
  Check as CheckIcon,
  Star as StarIcon,
  Business as BusinessIcon,
  AttachMoney as MoneyIcon,
  Group as GroupIcon,
  Storage as StorageIcon,
  Schedule as ScheduleIcon,
} from '@mui/icons-material';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useForm, Controller } from 'react-hook-form';

import {
  SubscriptionPlan,
  Tenant,
  PlanFeature,
  CreateSubscriptionPlanRequest,
  UpdateSubscriptionPlanRequest,
} from '@/types';
import { useAuth, useAppNotifications } from '@/stores';
import { tenantService } from '@/services/tenantService';
import { PageHeader } from '@/components/common/PageHeader';

interface TenantPlansPageProps {}

const TenantPlansPage: React.FC<TenantPlansPageProps> = () => {
  const { hasPermission } = useAuth();
  const { showToast } = useAppNotifications();
  const queryClient = useQueryClient();

  const [editingPlan, setEditingPlan] = useState<SubscriptionPlan | null>(null);
  const [dialogOpen, setDialogOpen] = useState(false);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [planToDelete, setPlanToDelete] = useState<SubscriptionPlan | null>(null);

  // 表单控制
  const { control, handleSubmit, reset, formState: { errors } } = useForm({
    defaultValues: {
      name: '',
      price: 0,
      billingCycle: 'monthly',
      maxUsers: 10,
      maxOrganizations: 1,
      maxStorage: 1024,
      features: [],
      description: '',
    },
  });

  // 获取订阅套餐列表
  const {
    data: plansData,
    isLoading,
    error,
  } = useQuery({
    queryKey: ['subscription-plans'],
    queryFn: () => tenantService.getSubscriptionPlans(),
  });

  // 获取租户列表（显示使用该套餐的租户）
  const { data: tenantsData } = useQuery({
    queryKey: ['tenants', { pageSize: 1000 }],
    queryFn: () => tenantService.getTenants({ pageSize: 1000 }),
  });

  // 创建套餐
  const createMutation = useMutation({
    mutationFn: (data: CreateSubscriptionPlanRequest) => 
      fetch('/api/subscription-plans', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data),
      }).then(res => res.json()),
    onSuccess: () => {
      showToast({ type: 'success', title: '创建成功', message: '订阅套餐已创建' });
      queryClient.invalidateQueries(['subscription-plans']);
      handleCloseDialog();
    },
    onError: (error: any) => {
      showToast({ type: 'error', title: '创建失败', message: error.message });
    },
  });

  // 更新套餐
  const updateMutation = useMutation({
    mutationFn: ({ id, data }: { id: string; data: UpdateSubscriptionPlanRequest }) =>
      fetch(`/api/subscription-plans/${id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data),
      }).then(res => res.json()),
    onSuccess: () => {
      showToast({ type: 'success', title: '更新成功', message: '订阅套餐已更新' });
      queryClient.invalidateQueries(['subscription-plans']);
      handleCloseDialog();
    },
    onError: (error: any) => {
      showToast({ type: 'error', title: '更新失败', message: error.message });
    },
  });

  // 删除套餐
  const deleteMutation = useMutation({
    mutationFn: (id: string) =>
      fetch(`/api/subscription-plans/${id}`, { method: 'DELETE' }),
    onSuccess: () => {
      showToast({ type: 'success', title: '删除成功', message: '订阅套餐已删除' });
      queryClient.invalidateQueries(['subscription-plans']);
      setDeleteDialogOpen(false);
      setPlanToDelete(null);
    },
    onError: (error: any) => {
      showToast({ type: 'error', title: '删除失败', message: error.message });
    },
  });

  // 处理创建/编辑
  const handleOpenDialog = (plan?: SubscriptionPlan) => {
    if (plan) {
      setEditingPlan(plan);
      reset({
        name: plan.name,
        price: plan.price,
        billingCycle: plan.billingCycle,
        maxUsers: plan.maxUsers,
        maxOrganizations: plan.maxOrganizations,
        maxStorage: plan.maxStorage,
        features: plan.features?.map(f => f.key) || [],
        description: plan.description || '',
      });
    } else {
      setEditingPlan(null);
      reset({
        name: '',
        price: 0,
        billingCycle: 'monthly',
        maxUsers: 10,
        maxOrganizations: 1,
        maxStorage: 1024,
        features: [],
        description: '',
      });
    }
    setDialogOpen(true);
  };

  const handleCloseDialog = () => {
    setDialogOpen(false);
    setEditingPlan(null);
    reset();
  };

  // 处理删除
  const handleDeletePlan = (plan: SubscriptionPlan) => {
    const usingTenants = tenantsData?.data?.filter(
      tenant => tenant.subscriptionPlanId === plan.id
    ) || [];

    if (usingTenants.length > 0) {
      showToast({
        type: 'warning',
        title: '无法删除',
        message: `该套餐正在被 ${usingTenants.length} 个租户使用，请先迁移这些租户`,
      });
      return;
    }

    setPlanToDelete(plan);
    setDeleteDialogOpen(true);
  };

  // 提交表单
  const onSubmit = (data: any) => {
    if (editingPlan) {
      updateMutation.mutate({ id: editingPlan.id, data });
    } else {
      createMutation.mutate(data);
    }
  };

  // 获取使用该套餐的租户数量
  const getTenantCount = (planId: string) => {
    return tenantsData?.data?.filter(
      tenant => tenant.subscriptionPlanId === planId
    ).length || 0;
  };

  // 可用功能列表
  const availableFeatures = [
    { key: 'analytics', name: '数据分析', icon: '📊' },
    { key: 'api_access', name: 'API 访问', icon: '🔌' },
    { key: 'custom_branding', name: '自定义品牌', icon: '🎨' },
    { key: 'advanced_security', name: '高级安全', icon: '🔒' },
    { key: 'priority_support', name: '优先支持', icon: '🚀' },
    { key: 'data_export', name: '数据导出', icon: '📤' },
    { key: 'sso', name: '单点登录', icon: '🔑' },
    { key: 'audit_logs', name: '审计日志', icon: '📝' },
  ];

  if (error) {
    return (
      <Box sx={{ p: 3 }}>
        <Alert severity="error">
          加载订阅套餐失败：{(error as any).message}
        </Alert>
      </Box>
    );
  }

  return (
    <Box sx={{ p: 3 }}>
      <PageHeader
        title="租户套餐管理"
        description="管理订阅套餐和定价方案"
        actions={
          hasPermission('subscription.create') ? (
            <Button
              variant="contained"
              startIcon={<AddIcon />}
              onClick={() => handleOpenDialog()}
            >
              创建套餐
            </Button>
          ) : undefined
        }
      />

      <Grid container spacing={3}>
        {plansData?.data?.map((plan) => {
          const tenantCount = getTenantCount(plan.id);
          
          return (
            <Grid item xs={12} md={6} lg={4} key={plan.id}>
              <Card 
                sx={{ 
                  height: '100%',
                  display: 'flex',
                  flexDirection: 'column',
                  position: 'relative',
                  ...(plan.isPopular && {
                    border: 2,
                    borderColor: 'primary.main',
                  }),
                }}
              >
                {plan.isPopular && (
                  <Chip
                    label="推荐"
                    color="primary"
                    size="small"
                    icon={<StarIcon />}
                    sx={{
                      position: 'absolute',
                      top: 16,
                      right: 16,
                    }}
                  />
                )}

                <CardContent sx={{ flex: 1 }}>
                  <Box sx={{ mb: 2 }}>
                    <Typography variant="h5" gutterBottom>
                      {plan.name}
                    </Typography>
                    <Typography variant="body2" color="text.secondary" gutterBottom>
                      {plan.description}
                    </Typography>
                    <Box sx={{ display: 'flex', alignItems: 'baseline', mb: 2 }}>
                      <Typography variant="h3" color="primary">
                        ¥{plan.price}
                      </Typography>
                      <Typography variant="body2" color="text.secondary" sx={{ ml: 1 }}>
                        /{plan.billingCycle === 'monthly' ? '月' : '年'}
                      </Typography>
                    </Box>
                  </Box>

                  <Divider sx={{ my: 2 }} />

                  {/* 套餐规格 */}
                  <Box sx={{ mb: 2 }}>
                    <List dense>
                      <ListItem disablePadding>
                        <ListItemIcon>
                          <GroupIcon color="primary" />
                        </ListItemIcon>
                        <ListItemText primary={`最多 ${plan.maxUsers} 个用户`} />
                      </ListItem>
                      <ListItem disablePadding>
                        <ListItemIcon>
                          <BusinessIcon color="primary" />
                        </ListItemIcon>
                        <ListItemText primary={`最多 ${plan.maxOrganizations} 个组织`} />
                      </ListItem>
                      <ListItem disablePadding>
                        <ListItemIcon>
                          <StorageIcon color="primary" />
                        </ListItemIcon>
                        <ListItemText primary={`${plan.maxStorage} MB 存储空间`} />
                      </ListItem>
                    </List>
                  </Box>

                  {/* 功能特性 */}
                  {plan.features && plan.features.length > 0 && (
                    <Box sx={{ mb: 2 }}>
                      <Typography variant="subtitle2" gutterBottom>
                        功能特性
                      </Typography>
                      <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.5 }}>
                        {plan.features.map((feature) => (
                          <Chip
                            key={feature.key}
                            label={feature.name}
                            size="small"
                            variant="outlined"
                            color="primary"
                          />
                        ))}
                      </Box>
                    </Box>
                  )}

                  {/* 使用统计 */}
                  <Box sx={{ mt: 'auto' }}>
                    <Chip
                      label={`${tenantCount} 个租户使用`}
                      size="small"
                      color={tenantCount > 0 ? 'success' : 'default'}
                    />
                  </Box>
                </CardContent>

                {/* 操作按钮 */}
                {(hasPermission('subscription.edit') || hasPermission('subscription.delete')) && (
                  <Box sx={{ p: 2, pt: 0 }}>
                    <Box sx={{ display: 'flex', gap: 1 }}>
                      {hasPermission('subscription.edit') && (
                        <Button
                          size="small"
                          startIcon={<EditIcon />}
                          onClick={() => handleOpenDialog(plan)}
                        >
                          编辑
                        </Button>
                      )}
                      {hasPermission('subscription.delete') && (
                        <Button
                          size="small"
                          color="error"
                          startIcon={<DeleteIcon />}
                          onClick={() => handleDeletePlan(plan)}
                          disabled={tenantCount > 0}
                        >
                          删除
                        </Button>
                      )}
                    </Box>
                  </Box>
                )}
              </Card>
            </Grid>
          );
        })}
      </Grid>

      {/* 创建/编辑对话框 */}
      <Dialog
        open={dialogOpen}
        onClose={handleCloseDialog}
        maxWidth="md"
        fullWidth
      >
        <form onSubmit={handleSubmit(onSubmit)}>
          <DialogTitle>
            {editingPlan ? '编辑套餐' : '创建套餐'}
          </DialogTitle>
          <DialogContent>
            <Grid container spacing={2} sx={{ mt: 1 }}>
              <Grid item xs={12} md={6}>
                <Controller
                  name="name"
                  control={control}
                  rules={{ required: '套餐名称不能为空' }}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="套餐名称"
                      fullWidth
                      error={!!errors.name}
                      helperText={errors.name?.message}
                    />
                  )}
                />
              </Grid>
              <Grid item xs={12} md={6}>
                <Controller
                  name="price"
                  control={control}
                  rules={{ required: '价格不能为空', min: { value: 0, message: '价格不能为负数' } }}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="价格"
                      type="number"
                      fullWidth
                      error={!!errors.price}
                      helperText={errors.price?.message}
                      InputProps={{
                        startAdornment: <MoneyIcon />,
                      }}
                    />
                  )}
                />
              </Grid>
              <Grid item xs={12} md={6}>
                <Controller
                  name="billingCycle"
                  control={control}
                  render={({ field }) => (
                    <FormControl fullWidth>
                      <InputLabel>计费周期</InputLabel>
                      <Select {...field} label="计费周期">
                        <MenuItem value="monthly">月付</MenuItem>
                        <MenuItem value="yearly">年付</MenuItem>
                      </Select>
                    </FormControl>
                  )}
                />
              </Grid>
              <Grid item xs={12} md={6}>
                <Controller
                  name="maxUsers"
                  control={control}
                  rules={{ required: '用户数限制不能为空', min: { value: 1, message: '用户数不能少于1' } }}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="用户数限制"
                      type="number"
                      fullWidth
                      error={!!errors.maxUsers}
                      helperText={errors.maxUsers?.message}
                    />
                  )}
                />
              </Grid>
              <Grid item xs={12} md={6}>
                <Controller
                  name="maxOrganizations"
                  control={control}
                  rules={{ required: '组织数限制不能为空', min: { value: 1, message: '组织数不能少于1' } }}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="组织数限制"
                      type="number"
                      fullWidth
                      error={!!errors.maxOrganizations}
                      helperText={errors.maxOrganizations?.message}
                    />
                  )}
                />
              </Grid>
              <Grid item xs={12} md={6}>
                <Controller
                  name="maxStorage"
                  control={control}
                  rules={{ required: '存储限制不能为空', min: { value: 100, message: '存储不能少于100MB' } }}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="存储限制 (MB)"
                      type="number"
                      fullWidth
                      error={!!errors.maxStorage}
                      helperText={errors.maxStorage?.message}
                    />
                  )}
                />
              </Grid>
              <Grid item xs={12}>
                <Controller
                  name="description"
                  control={control}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="套餐描述"
                      multiline
                      rows={3}
                      fullWidth
                    />
                  )}
                />
              </Grid>
              <Grid item xs={12}>
                <Controller
                  name="features"
                  control={control}
                  render={({ field }) => (
                    <FormControl fullWidth>
                      <InputLabel>功能特性</InputLabel>
                      <Select
                        {...field}
                        multiple
                        label="功能特性"
                        renderValue={(selected) => (
                          <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.5 }}>
                            {(selected as string[]).map((value) => {
                              const feature = availableFeatures.find(f => f.key === value);
                              return (
                                <Chip
                                  key={value}
                                  label={feature?.name || value}
                                  size="small"
                                />
                              );
                            })}
                          </Box>
                        )}
                      >
                        {availableFeatures.map((feature) => (
                          <MenuItem key={feature.key} value={feature.key}>
                            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                              <span>{feature.icon}</span>
                              <span>{feature.name}</span>
                            </Box>
                          </MenuItem>
                        ))}
                      </Select>
                    </FormControl>
                  )}
                />
              </Grid>
            </Grid>
          </DialogContent>
          <DialogActions>
            <Button onClick={handleCloseDialog}>取消</Button>
            <Button
              type="submit"
              variant="contained"
              disabled={createMutation.isLoading || updateMutation.isLoading}
            >
              {editingPlan ? '更新' : '创建'}
            </Button>
          </DialogActions>
        </form>
      </Dialog>

      {/* 删除确认对话框 */}
      <Dialog
        open={deleteDialogOpen}
        onClose={() => setDeleteDialogOpen(false)}
      >
        <DialogTitle>确认删除</DialogTitle>
        <DialogContent>
          <Typography>
            确定要删除套餐 "{planToDelete?.name}" 吗？此操作不可撤销。
          </Typography>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setDeleteDialogOpen(false)}>取消</Button>
          <Button
            color="error"
            onClick={() => planToDelete && deleteMutation.mutate(planToDelete.id)}
            disabled={deleteMutation.isLoading}
          >
            删除
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default TenantPlansPage;